/*
 * Copyright 2003-2005 (c) Live Media Pty Ltd. <argot@einet.com.au> 
 *
 * This software is licensed under the Argot Public License 
 * which may be found in the file LICENSE distributed 
 * with this software.
 *
 * More information about this license can be found at
 * http://www.einet.com.au/License
 * 
 * The Developer of this software is Live Media Pty Ltd,
 * PO Box 4591, Melbourne 3001, Australia.  The license is subject 
 * to the law of Victoria, Australia, and subject to exclusive 
 * jurisdiction of the Victorian courts.
 */

using System;

using TypeElement = argot.TypeElement;
using TypeException = argot.TypeException;
using TypeInputStream = argot.TypeInputStream;
using TypeOutputStream = argot.TypeOutputStream;
using TypeReader = argot.TypeReader;
using TypeReaderAuto = argot.TypeReaderAuto;
using TypeWriter = argot.TypeWriter;

namespace argot.meta
{
	
	public class MetaOptional:MetaBase, TypeReader, TypeWriter, MetaExpression
	{
		public static System.String TYPENAME = "meta.optional";
		
		private MetaExpression _option;
		
		public MetaOptional(MetaExpression option)
		{
			_option = option;
		}

		override public System.String TypeName
		{
			get
			{
				return TYPENAME;
			}
			
		}
		virtual public MetaExpression OptionalExpression
		{
			get
			{
				return _option;
			}
			
		}
		
		public virtual System.Object Read(TypeInputStream inStream, TypeElement element)
		{
			TypeReader reader = new TypeReaderAuto(this.GetType());
			return reader.Read(inStream, element);
		}
		
		public virtual void Write(TypeOutputStream outStream, System.Object o, TypeElement element)
		{
			MetaOptional to = (MetaOptional) o;
			
			outStream.WriteObject("meta.name", to._option);
		}
		
		public virtual System.Object DoRead(TypeInputStream inStream)
		{
			System.Boolean id = (System.Boolean) inStream.ReadObject("bool");
			if (id)
				return _option.DoRead(inStream);
			return null;
		}
		
		public virtual void DoWrite(TypeOutputStream outStream, System.Object o)
		{
			if (o == null)
			{
				outStream.WriteObject("bool", (System.Object) false);
				return ;
			}
			
			outStream.WriteObject("bool", (System.Object) true);
			_option.DoWrite(outStream, o);
		}
	}
}